package main

import (
	"fmt"
	"strconv"
)

//按位相加，用时超过100%，内存超过77%
func addBinary(a string, b string) string {
	if len(a) < len(b) {
		a, b = b, a
	}
	aLen, bLen := len(a), len(b)
	sub := aLen - bLen
	var carry byte = 0
	var res byte = 0
	s := []rune{}
	for i := aLen - 1; i >= 0; i-- {
		if i >= sub {
			res = a[i] + b[i-sub] + carry - 96
		} else {
			res = a[i] + carry - 48
		}
		if res == 0 {
			s = append(s, 48)
		} else if res == 1 {
			s = append(s, 49)
			carry = 0
		} else if res == 2 {
			s = append(s, 48)
			carry = 1
		} else if res == 3 {
			s = append(s, 49)
			carry = 1
		}
	}
	if carry == 1 {
		s = append(s, 49)
	}
	for i := 0; i < len(s)/2; i++ {
		s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i]
	}
	return string(s)
}

//转换相加,用时超过27%，内存超过77%
func addBinary1(a string, b string) string {
	a1, b1 := 0, 0
	for i := 0; i < len(a); i++ {
		if a[i] == 49 {
			a1 += 1 << i
		}
	}
	for i := 0; i < len(b); i++ {
		if b[i] == 49 {
			b1 += 1 << i
		}
	}
	result := ""
	for res := a1 + b1; res > 0; res /= 2 {
		tmp := res % 2
		result = strconv.Itoa(tmp) + result
	}
	return result
}

func main() {
	a := "1111"
	b := "1111"
	fmt.Println(len(a), len(b))
	fmt.Println(addBinary(a, b))
	fmt.Println(addBinary1(a, b))
}
